"use strict";

var webpack = require("webpack");
var path = require("path");
var glob = require("glob");

//路径定义
var srcDir = path.resolve(process.cwd(), "src");
var distDir = path.resolve(process.cwd(), "dist");
var nodeModPath = path.resolve(__dirname, "./node_modules");
//插件定义
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var HtmlWebpackPlugin = require("html-webpack-plugin");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var cleanWebpackPlugin = require("clean-webpack-plugin");
var AddAssetHtmlCdnWebpackPlugin = require('add-asset-html-cdn-webpack-plugin');

module.exports = function () {
  var plugins = [];
  var extractCSS;

  extractCSS = new ExtractTextPlugin({
    filename: "assets/css/[name].css",
    allChunks: true,
  });
  plugins.push(
    extractCSS,
    new cleanWebpackPlugin(["dist/*"], {
      root: path.resolve(__dirname),
    }),
    new webpack.NoEmitOnErrorsPlugin(),
    new CommonsChunkPlugin({
      name: "vendor",
      minChunks: 2,
    }),
    new AddAssetHtmlCdnWebpackPlugin(true, {
      jquery: 'https://s1.pstatp.com/cdn/expire-1-M/jquery/1.12.0/jquery.min.js',
      mui: 'https://s1.pstatp.com/cdn/expire-1-M/mui/3.7.1/js/mui.min.js',
      // muiCss: 'https://s3.pstatp.com/cdn/expire-1-M/mui/3.7.1/css/mui.min.css'
    })
    // new webpack.optimize.UglifyJsPlugin({
    //   test: /\.js($|\?)/,
    //   include: /\/js\/vendor\.js/
    // })
  );

  //config
  var config = {
    entry: Object.assign(entries(), {
      // 用到什么公共lib（例如jquery.js），就把它加进vendor去，目的是将公用库单独提取打包
      vendor: ["jquery", "mui"],
    }),
    output: {
      path: path.join(__dirname, "dist"),
      filename: "assets/js/[name].js",
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          loader: "babel-loader",
        },
        {
          test: /\.((woff2?|svg)(\?v=[0-9]\.[0-9]\.[0-9]))|(woff2?|svg|jpe?g|png|gif|ico)$/,
          use: [
            {
              loader: "url-loader",
              options: {
                esModule: false,
                name: "assets/img/[name].[ext]",
                limit: 10,
              },
            },
          ],
        },
        {
          test: /\.((ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9]))|(ttf|eot)$/,
          use: "url-loader?limit=10000&name=assets/fonts/[hash:8].[name].[ext]",
        },
        { test: /\.(tpl|ejs)$/, use: "ejs-loader" },
        {
          test: /\.(css|scss)$/,
          use: extractCSS.extract({
            use: ["css-loader", "autoprefixer-loader", "sass-loader"],
            fallback: "style-loader",
            publicPath: "../../",
          }),
        },
      ],
    },
    resolve: {
      extensions: [".js", ".css", ".scss", ".tpl", ".png", ".jpg"],
      modules: [srcDir, nodeModPath],
      alias: {
        // jquery: "js/lib/jquery-1.12.4.js",
        utils: "js/ht/utils.js",
        // mui: "js/lib/mui.min.js",
        commonJs: "js/ht/common.js",
        commonCss: "css/common.scss",
        muiCss: "css/mui.min.css",
        "@": path.join(__dirname, "src"),
      },
    },
    externals: {
      'jquery': '$',
      'mui': 'mui'
    },
    plugins: plugins.concat(html_plugins()),
  };

  return config;
};

//入口文件定义
var entries = function () {
  var jsDir = path.resolve(srcDir, "js");
  var entryFiles = glob.sync(jsDir + "/*.{js,jsx}");
  var map = {};

  for (var i = 0; i < entryFiles.length; i++) {
    var filePath = entryFiles[i];
    var filename = filePath.substring(
      filePath.lastIndexOf("/") + 1,
      filePath.lastIndexOf(".")
    );
    map[filename] = filePath;
  }
  return map;
};
//html_webpack_plugins 定义
var html_plugins = function () {
  var entryHtml = glob.sync(srcDir + "/*.ejs");
  var r = [];
  var entriesFiles = entries();
  for (var i = 0; i < entryHtml.length; i++) {
    var filePath = entryHtml[i];
    var filename = filePath.substring(
      filePath.lastIndexOf("/") + 1,
      filePath.lastIndexOf(".")
    );
    var conf = {
      template: filePath,
      filename: filename + ".html",
    };
    //如果和入口js文件同名
    if (filename in entriesFiles) {
      conf.inject = "body";
      conf.chunks = ["vendor", filename];
    }
    r.push(new HtmlWebpackPlugin(conf));
  }
  return r;
};
